<template>
  <view class="relative">
    <view
      class="ball"
      v-for="(d, i) in balls"
      :key="i"
      :style="
        d.inited
          ? `transition: transform .5s ease-in; transform: translate3d(0, ${offsetY}px,0); top: ${ballY}px;`
          : ''
      "
    >
      <view
        class="inner arbg"
        :style="
          d.inited
            ? `transition: transform .5s linear; transform: translate3d( ${offsetX}px,0,0); left: ${ballX}px; opacity: 1;`
            : ''
        "
      ></view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 定义 props
const props = defineProps<{
  cartBasketRect: any
}>()

// 定义响应式数据
const offsetX = ref(0)
const offsetY = ref(0)
const ballX = ref(0)
const ballY = ref(0)
const balls = ref<{ inited: boolean }[]>([])
const lastEvent = ref<MouseEvent | null>(null)
const lastId = ref('')

// 初始化 balls 数组
onMounted(() => {
  for (let i = 0; i < 5; i++) {
    balls.value.push({ inited: false })
  }
})

// 获取 balls 数组
const getBalls = () => {
  return balls.value
}

// 添加商品到购物车的方法
const addToCart = (e: any, id: string) => {
  if (!id) {
    lastId.value = ''
    return
  }

  lastId.value = id
  lastEvent.value = e
  // if (lastId.value === id) {
  //   e = lastEvent.value as any
  // } else {
  //   lastId.value = id
  //   lastEvent.value = e
  // }

  // 微信 app 等可能偏移，可以根据需要微调
  const clientX = e.touches?.[0]?.clientX || e.clientX
  const clientY = e.touches?.[0]?.clientY || e.clientY
  ballX.value = clientX - 10
  ballY.value = clientY - 9
  if (props.cartBasketRect) {
    offsetX.value = -Math.abs(props.cartBasketRect.left - ballX.value + 10)
    offsetY.value = Math.abs(
      props.cartBasketRect.top - ballY.value + props.cartBasketRect.height / 1.5,
    )
  }

  for (let i = 0; i < 5; i++) {
    if (!balls.value[i].inited) {
      balls.value[i].inited = true
      setTimeout(() => {
        balls.value[i].inited = false
      }, 500)
      break
    }
  }
}

// 暴露 addToCart 方法给父组件
defineExpose({
  addToCart,
})
</script>

<style lang="scss">
.ball {
  position: fixed;
  background-color: red;
  z-index: 99999;
  .inner {
    background: #ff9900;
    width: 30rpx;
    height: 30rpx;
    position: fixed;
    border-radius: 50%;
    opacity: 0;
  }
}
</style>
